package com.jay.tools.web.webview;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;

/**
 * Created by tan on 2017/9/22 022.
 */

public class WebVeiwSetting {

    @SuppressLint("SetJavaScriptEnabled")
    public WebView createWebView(WebView webView) {
        // API大于19才能用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        cookieSet(webView);

        // 禁止横纵向滚动
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);
        // 允许截图
        webView.setDrawingCacheEnabled(true);

        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
//                return true;// 屏蔽长按
                return false; // 允许长按，实现文字复制
            }
        });

        initSettings(webView);

        return webView;
    }

    private void cookieSet(WebView webView) {
        //Cookie浏览器在本地存储用户信息，有域名限制，不同域名下的cookie不能相互访问
        // Cookie的拦截在OkHttp3中进行
        final CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 开启跨域cookie，5.0前默认开启
            cookieManager.setAcceptThirdPartyCookies(webView, true);
        }
        CookieManager.setAcceptFileSchemeCookies(true);
    }

    private void initSettings(WebView webView) {
        final WebSettings settings = webView.getSettings();

        // 是JS代码中的交互事件生效
        settings.setJavaScriptEnabled(true);

        final String ua = settings.getUserAgentString();
        // 判断是否是自己的APP打开网页
        settings.setUserAgentString(ua + "latte");

        //隐藏缩放控件
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        // 禁止缩放
        settings.setSupportZoom(false);

        // 文件权限
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        // API大于16可以使用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
            settings.setAllowUniversalAccessFromFileURLs(true);
        }

        // 缓存相关
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }


}
